import toast from './index.vue'

export default {
  toastTimer: null,
  toastExtend: null,
  defaultConfig: {
    type: 'default', //  提示类型 success | fail | cross | loading
    text: '', //  提示文字
    duration: 2000, //  提示时长
    forbidClick: false //  是否禁用背景点击
  },
  install (Vue, options) {
    //  支持可修改默认配置
    if (options) this.defaultConfig = Object.assign({}, this.defaultConfig, options)

    Vue.prototype.$toast2 = (config, type) => {
      let options = this.defaultConfig
      //  支持简写模式 this.$toast('文本内容')
      if (typeof config === 'string') {
        options.text = config
      } else {
        Object.assign(options, config)
      }

      if (type) {
        options.type = type
      }

      //  如果 type 不是指定类型，那么就自动转换成默认类型
      if (!['success', 'fail', 'error', 'loading'].includes(options.type)) {
        options.type = 'default'
      }

      //  如果还有没执行完的toast，清除上次提示框的计时器重新计时
      if (this.toastTimer) {
        clearTimeout(this.toastTimer)
        this.toastTimer = null
      }

      //  判断是否有 bk-toast的div
      if (!this.toastExtend) {
        console.log(toast)
        let ToastExtend = Vue.extend(toast)
        this.toastExtend = new ToastExtend()
        this.toastExtend.$mount('#bk-toast')
      }

      this.toastExtend.show = true
      this.toastExtend.forbidClick = options.forbidClick
      this.toastExtend.type = options.type
      this.toastExtend.text = options.text

      this.toastTimer = setTimeout(() => {
        this.toastExtend.show = false
        this.toastTimer = null
      }, options.duration)
    }
    Vue.prototype.$toast2['success'] = config => Vue.prototype.$toast2(config, 'success')
    Vue.prototype.$toast2['fail'] = config => Vue.prototype.$toast2(config, 'fail')
    Vue.prototype.$toast2['error'] = config => Vue.prototype.$toast2(config, 'error')
    Vue.prototype.$toast2['loading'] = config => Vue.prototype.$toast2(config, 'loading')
  }
}
